package com.jl.utils.netty;


import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.enums.ReadyState;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.net.URISyntaxException;


@Slf4j
public class JavaWebSocketClient {

    public WebSocketClient client;

    public JavaWebSocketClient(){

    }

    public WebSocketClient connect() {
        try {
            client = new WebSocketClient(new URI("ws://localhost:8888/ws"), new Draft_6455(),null,10000) {
                @Override
                public void onOpen(ServerHandshake serverHandshake) {
                    log.info("握手成功");
                }

                @Override
                public void onMessage(String msg) {
                    log.info("JavaSocket收到消息==========" + msg);
                    if (msg.equals("over")) {
                        log.info("over???");
                        client.close();
                    }
                }

                @Override
                public void onClose(int i, String s, boolean b) {
                    log.info("链接已关闭");
                }

                @Override
                public void onError(Exception e) {
                    e.printStackTrace();
                    log.info("发生错误已关闭");
                }
            };
        } catch (URISyntaxException e) {
            log.info("意外断开!!!");
            e.printStackTrace();
            client.close();
        }
        client.connect();
//      log.info(client.getDraft());
        int count = 0;
        while (client.getReadyState().equals(ReadyState.NOT_YET_CONNECTED)){
            try {
                Thread.sleep(500);
                count++;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.info("为什么没连上{}?",count);
            if (count==6){
                client.close();
            }
        }
        return client;
    }

}
